package com.youlu.campus.service.course;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.mongodb.client.result.UpdateResult;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.common.utils.IdGeneratorUtils;
import com.youlu.campus.entity.*;
import com.youlu.campus.entity.VO.req.CourseOrderRefundApplyReq;
import com.youlu.campus.entity.commission.DistributorApply;
import com.youlu.campus.entity.commission.DistributorCommission;
import com.youlu.campus.entity.commission.dto.DistributorChannelSharingCommissionOrderDTO;
import com.youlu.campus.entity.commission.dto.SharingCommissionOrderDTO;
import com.youlu.campus.entity.course.ActivityCourse;
import com.youlu.campus.entity.course.CourseOrderRefundApply;
import com.youlu.campus.entity.course.UserCourseOrder;
import com.youlu.campus.entity.course.dto.CourseInfoDTO;
import com.youlu.campus.entity.course.dto.GoodsOrderDTO;
import com.youlu.campus.entity.enums.CourseOrderStatusEnum;
import com.youlu.campus.entity.enums.CourseOrderTypeEnum;
import com.youlu.campus.entity.enums.SharingProfitOrderTypeEnum;
import com.youlu.campus.service.activity.UserParticipateActivityInfoService;
import com.youlu.campus.service.activity.WechatMiniQaService;
import com.youlu.campus.service.base.BaseService;
import com.youlu.campus.service.ca.UserCaService;
import com.youlu.campus.service.cache.CacheUserService;
import com.youlu.campus.service.commission.CourseOrderCommissionServiceService;
import com.youlu.campus.service.commission.DistributorChannelSharingCommissionService;
import com.youlu.campus.service.invite.UserInviteRecordService;
import com.youlu.campus.service.order.MerchantSharingProfitService;
import com.youlu.campus.service.qa.UserQaInfoService;
import com.youlu.campus.service.visitor.UserPointsCourseStudyService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Triple;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.sql.Date;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author : [dengbo]
 * @className : UserCourseOrderService
 * @description : [用户课程订单]
 * @createTime : [2022/5/19 14:50]
 */
@Service
@Slf4j
public class UserCourseOrderService extends BaseService {
    /**
     * 单位s 订单默认有效时间5天
     */
    private static final long ORDER_EXPIRE_TIME = 3600 * 24 * 5;

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private UserVideoService userVideoService;
    @Autowired
    private WechatPayService wechatPayService;
    @Autowired
    private UserQaInfoService userQaInfoService;
    @Autowired
    private UserCaService userCaService;
    @Autowired
    private UserPointsCourseStudyService userPointsCourseStudyService;
    @Autowired
    private UserParticipateActivityInfoService userParticipateActivityInfoService;
    @Autowired
    private CacheUserService cacheUserService;
    @Autowired
    private WechatMiniQaService wechatMiniQaService;
    @Autowired
    private UserInviteRecordService userInviteRecordService;

    @Autowired
    private MerchantSharingProfitService merchantSharingProfitService;

    @Autowired
    private CourseOrderCommissionServiceService courseOrderCommissionServiceService;

    @Autowired
    private DistributorChannelSharingCommissionService distributorChannelSharingCommissionService;

    /**
     * 获取用户是否购买
     *
     * @param userId
     * @return
     */
    public Boolean getBuyOrderByUserId(String userId) {
        // 获取支付订单
        List<Integer> statusList = Lists.newArrayList(CourseOrderStatusEnum.PAY_SUCCESS.getValue(), CourseOrderStatusEnum.REFUND_APPLY.getValue(), CourseOrderStatusEnum.REFUND_COMPLETE.getValue());
        Query query = new Query(Criteria.where("userId").is(userId).and("status").in(statusList));
        return this.mongoTemplate.exists(query, UserCourseOrder.class);
    }

    public Triple<Boolean, Object, String> getPayInfoOld(CourseInfoDTO dto, ActivityCourse activityCourse) {
        // 获取有效的订单
        UserCourseOrder courseOrder = getExpireOrderByUserId(dto.getUserId(), dto.getAppId(), dto.getActivityId(),
                dto.getCourseId());
        if (courseOrder == null) {
            return createOrder(dto, activityCourse);
        }
        if (courseOrder.getStatus().equals(CourseOrderStatusEnum.PAY_SUCCESS.getValue())) {
            return Triple.of(false, null, "已经支付过了");
        }
        if (courseOrder.getStatus().equals(CourseOrderStatusEnum.REFUND_APPLY.getValue())) {
            return Triple.of(false, null, "退款申请中不能支付");
        }
        if (LocalDateTime.now().isAfter(courseOrder.getExpireTime())) {
            // 订单失效
            boolean re = updateOrderExpire(courseOrder);
            if (!re) {
                return Triple.of(false, null, "服务异常,请重试");
            }
            // 重新创建
            return createOrder(dto, activityCourse);
        }
        return Triple.of(true, courseOrder.getPayInfo(), null);
    }

    public Triple<Boolean, Object, String> getPayInfo(CourseInfoDTO dto, ActivityCourse activityCourse) {
        // 获取支付订单
        List<Integer> statusList = Lists.newArrayList(CourseOrderStatusEnum.PAY_SUCCESS.getValue(),
                CourseOrderStatusEnum.REFUND_APPLY.getValue());
        UserCourseOrder courseOrder = getOrderByUserIdAndStatus(dto.getUserId(), dto.getAppId(), dto.getCourseId(),
                statusList);
        if (courseOrder != null) {
            if (courseOrder.getStatus().equals(CourseOrderStatusEnum.PAY_SUCCESS.getValue())) {
                return Triple.of(false, null, "已经支付过了");
            } else {
                return Triple.of(false, null, "退款申请中不能支付");
            }
        }
        return createOrder(dto, activityCourse);
    }

    public Triple<Boolean, Object, String> createOrder(CourseInfoDTO dto, ActivityCourse activityCourse) {
        UserPO userPO = dto.getUserPO();
        UserCourseOrder courseOrder = buildCourseOrder(dto, activityCourse);
        // 获取商户信息
        WechatMerchantConfig merchantInfo = wechatPayService.getRandomMerchant(userPO.getAppId());
        courseOrder.setMerchantId(merchantInfo.getMerchantId());
        courseOrder.setMerchantName(merchantInfo.getMerchantName());
        courseOrder.setActivityChannelId(dto.getActivityChannelId());
        // 获取支付凭证
        Triple<Boolean, Object, String> result = wechatPayService.unifiedOrder(buildGoodsOrderParam(courseOrder),
                merchantInfo, dto.getNotifyUrl());
        if (result.getLeft()) {
            // 创建新的订单
            courseOrder.setPayInfo(result.getMiddle());
            insert(courseOrder);
        }
        return result;
    }

    public GoodsOrderDTO buildGoodsOrderParam(UserCourseOrder order) {
        GoodsOrderDTO dto = new GoodsOrderDTO();
        dto.setOrderNo(order.getOrderNo());
        dto.setClientIp(order.getClientIp());
        //dto.setStartTime(order.getStartTime());
        //dto.setStartTime(order.getExpireTime());
        dto.setOpenId(order.getOpenId());
        dto.setGoodsName(order.getName());
        dto.setPrice(order.getPrice());
        dto.setUserId(order.getUserId());
        dto.setAppId(order.getAppId());
        dto.setProfitSharing(true);
        return dto;
    }

    public Object payTest(String notifyUrl) {
        Query courseOrderQuery = new Query(Criteria.where("userId").is("60d0779bff34155eaf11e26c")
                .and("courseId").is("6282361d37e3c02f9cc3bebc")
                .and("status").is(CourseOrderStatusEnum.NOT_PAY.getValue()));
        UserCourseOrder courseOrder = mongoTemplate.findOne(courseOrderQuery, UserCourseOrder.class);
        if (courseOrder == null) {
            return null;
        }
        // 获取商户信息
        WechatMerchantConfig merchantInfo = wechatPayService.getWechatMerchantConfigById(courseOrder.getMerchantId());
        return courseOrder.getPayInfo();
    }


    public UserCourseOrder buildCourseOrder(CourseInfoDTO dto, ActivityCourse activityCourse) {
        UserPO userPO = dto.getUserPO();
        //获取支付凭证
        UserCourseOrder courseOrder = new UserCourseOrder();
        courseOrder.setUserId(userPO.getId());
        courseOrder.setStatus(CourseOrderStatusEnum.NOT_PAY.getValue());
        courseOrder.setPrice(activityCourse.getPrice());
        courseOrder.setCourseOrderType(dto.getCourseOrderType());
        courseOrder.setQaInfoId(dto.getQaInfoId());
        courseOrder.setName(activityCourse.getName());
        courseOrder.setCourseId(dto.getCourseId());
        courseOrder.setActivityId(dto.getActivityId());
        String orderNo = "";
        if (CourseOrderTypeEnum.VIDEO.getValue() == dto.getCourseOrderType()) {
            orderNo = IdGeneratorUtils.generateCourseNo();
        } else {
            orderNo = IdGeneratorUtils.generateContestNo();
        }

        courseOrder.setOrderNo(orderNo);
        courseOrder.setAppId(userPO.getAppId());
        courseOrder.setPlatform(userPO.getCurrentPlatform());
        courseOrder.setOpenId(userPO.getOpenId());
        courseOrder.setUnionId(userPO.getUnionId());
        courseOrder.setPhone(userPO.getMobile());
        courseOrder.setNickName(userPO.getNickName());
        courseOrder.setClientIp(dto.getClientIp());
        LocalDateTime now = LocalDateTime.now();
        courseOrder.setStartTime(now);
        LocalDateTime expireTime = now.plus(ORDER_EXPIRE_TIME, ChronoUnit.SECONDS);
        courseOrder.setExpireTime(expireTime);
        return courseOrder;
    }

    public UserCourseOrder insert(UserCourseOrder courseOrder) {
        return mongoTemplate.insert(courseOrder);
    }

    public List<UserCourseOrder> getOrderByUserId(String userId, String courseId) {
        Query courseOrderQuery = new Query(Criteria.where("userId").is(userId).and("courseId").is(courseId));
        return mongoTemplate.find(courseOrderQuery, UserCourseOrder.class);
    }

    /**
     * 获取有效订单
     *
     * @param userId
     * @param appId
     * @param activityId
     * @param courseId
     * @return
     */
    public UserCourseOrder getExpireOrderByUserId(String userId, String appId, String activityId, String courseId) {
        List<Integer> statusList = Lists.newArrayList(CourseOrderStatusEnum.NOT_PAY.getValue(),
                CourseOrderStatusEnum.PAY_SUCCESS.getValue(), CourseOrderStatusEnum.REFUND_APPLY.getValue());
        return getOrderByUserIdAndStatus(userId, appId, courseId, statusList);
    }

    /**
     * 获取订单
     *
     * @param userId
     * @param appId
     * @param courseId
     * @param statusList
     * @return
     */
    public UserCourseOrder getOrderByUserIdAndStatus(String userId, String appId, String courseId,
                                                     List<Integer> statusList) {
        Query courseOrderQuery =
                new Query(Criteria.where("userId").is(userId).and("appId").is(appId).and("courseId").is(courseId).and("status").in(statusList));
        return mongoTemplate.findOne(courseOrderQuery, UserCourseOrder.class);
    }

    public UserCourseOrder getOrderByOrderNo(String orderNo) {
        return mongoTemplate.findOne(new Query(Criteria.where("orderNo").is(orderNo)), UserCourseOrder.class);
    }

    /**
     * 处理支付回调
     *
     * @param orderNo
     * @param transactionId
     */
    public void dealOrderPaySuccess(String orderNo, String transactionId) {
        UserCourseOrder order = getOrderByOrderNo(orderNo);
        log.info("UserCourseOrderService,dealOrderPaySuccess,before deal order orderNo:{} orderStatus:{}", orderNo,
                order.getStatus());
        if (order == null) {
            log.warn("UserCourseOrderService,dealOrderPaySuccess,orderNo:{} not exist", orderNo);
            return;
        }
        CourseOrderStatusEnum statusEnum = CourseOrderStatusEnum.getByType(order.getStatus());
        switch (statusEnum) {
            case PAY_SUCCESS:
                log.warn("UserCourseOrderService,dealOrderPaySuccess,orderNo:{} has pay success", orderNo);
                return;
            case REFUND_APPLY:
                log.warn("UserCourseOrderService,dealOrderPaySuccess,orderNo:{} refund apply", orderNo);
                return;
            case REFUND_COMPLETE:
                log.warn("UserCourseOrderService,dealOrderPaySuccess,orderNo:{} has refund success", orderNo);
                return;
            case PAY_FIAL:
                log.warn("UserCourseOrderService,dealOrderPaySuccess,orderNo:{} pay fail", orderNo);
                return;
            case NOT_PAY:
                // 失效如果支付成功了，也处理
            case EXPIRED:
                // 更新订单状态
                order.setStatus(CourseOrderStatusEnum.PAY_SUCCESS.getValue());
                order.setPayTime(LocalDateTime.now());
                order.setTransactionId(transactionId);
                mongoTemplate.save(order);
                // 报名活动课程
                Triple<Boolean, Object, String> result = userVideoService.dealUserJoinActivity(order.getAppId(),
                        order.getUserId(), order.getActivityId(), order.getCourseId());
                if (result.getLeft()) {
                    // 查询用户信息
                    UserPO userPO = cacheUserService.findById(order.getUserId());
                    // 添加积分
                    userPointsCourseStudyService.endStudy(userPO, order.getUserId(), order.getPlatform(),
                            order.getAppId(), order.getOrderNo());
                    // 添加报名信息
                    //标识别报名信息时
                    userPO.setSignUpVideo(Boolean.TRUE);
                    userPO.setCurrentPlatform(order.getPlatform());
                    userPO.setAppId(order.getAppId());
                    userPO.setActivityChannelId(order.getActivityChannelId());
                    userPO.setOpenId(order.getOpenId());
                    userPO.setUnionId(order.getUnionId());
                    wechatMiniQaService.updateAfterSignUpUserInfo(order.getActivityId(), userPO);
                    if (StringUtils.isBlank(order.getActivityChannelId())) {
                        userInviteRecordService.updateInvitedStatus(order.getUserId(), order.getActivityId());
                    }
                }
                Integer sharingCommissionOrderAmount = 0;
                Integer sharingCommissionChannelOrderAmount = 0;
                //总订单金额减去分拥订单后金额
                Integer orderAmountAfter = 0;
                //分拥-个人
                UserInviteRecord userInviteRecord = courseOrderCommissionServiceService.inviterDistributor(order.getUserId(), order.getActivityId());
                if (Objects.nonNull(userInviteRecord) && userInviteRecord.getInviterDistributor()) {
                    DistributorApply distributorApply = courseOrderCommissionServiceService.findByDistributorId(userInviteRecord.getInvitedByUserId());
                    if (Objects.nonNull(distributorApply)) {
                        SharingCommissionOrderDTO sharingCommissionOrderDto = new SharingCommissionOrderDTO();
                        sharingCommissionOrderDto.setActivityId(order.getActivityId());
                        sharingCommissionOrderDto.setAppId(order.getAppId());
                        sharingCommissionOrderDto.setDistributorCommission(distributorApply.getDistributorCommission());
                        sharingCommissionOrderDto.setMerchantId(order.getMerchantId());
                        sharingCommissionOrderDto.setMerchantName(order.getMerchantName());
                        sharingCommissionOrderDto.setOrderNo(orderNo);
                        sharingCommissionOrderDto.setTotalFee(order.getPrice());
                        sharingCommissionOrderDto.setPayTime(Date.from(order.getPayTime().atZone(ZoneId.systemDefault()).toInstant()));
                        sharingCommissionOrderDto.setTransactionId(transactionId);
                        sharingCommissionOrderDto.setCategory(SharingProfitOrderTypeEnum.VIDEO_ORDER.name());
                        sharingCommissionOrderAmount = courseOrderCommissionServiceService.doSharingCommissionAmount(sharingCommissionOrderDto);
                    }
                } else {
                    //渠道分拥
                    String activityChannelId = order.getActivityChannelId();
                    if (StringUtils.isNotBlank(activityChannelId)) {
                        DistributorChannelSharingCommissionOrderDTO sharingCommissionOrderChannelDto =
                                new DistributorChannelSharingCommissionOrderDTO();
                        sharingCommissionOrderChannelDto.setActivityId(order.getActivityId());
                        sharingCommissionOrderChannelDto.setAppId(order.getAppId());
                        sharingCommissionOrderChannelDto.setMerchantId(order.getMerchantId());
                        sharingCommissionOrderChannelDto.setOrderNo(orderNo);
                        sharingCommissionOrderChannelDto.setMerchantName(order.getMerchantName());
                        sharingCommissionOrderChannelDto.setActivityChannelId(activityChannelId);
                        sharingCommissionOrderChannelDto.setPayTime(Date.from(order.getPayTime().atZone(ZoneId.systemDefault()).toInstant()));
                        sharingCommissionOrderChannelDto.setTotalFee(order.getPrice());
                        sharingCommissionOrderChannelDto.setTransactionId(transactionId);
                        sharingCommissionOrderChannelDto.setCategory(SharingProfitOrderTypeEnum.VIDEO_ORDER.name());
                        sharingCommissionOrderChannelDto.setUserId(order.getUserId());
                        sharingCommissionOrderChannelDto.setMobile(order.getPhone());
                        sharingCommissionOrderChannelDto.setName(order.getName());
                        UserParticipateActivityInfo user = userParticipateActivityInfoService.findByUserIdActivityId(order.getUserId(), order.getActivityId());
                        if (Objects.nonNull(user)) {
                            sharingCommissionOrderChannelDto.setUniversityId(user.getUniversityId());
                            sharingCommissionOrderChannelDto.setUniversityName(user.getUniversityName());
                        }
                        sharingCommissionChannelOrderAmount = distributorChannelSharingCommissionService.doSharingCommissionAmount(sharingCommissionOrderChannelDto);
                    }
                }
                if (sharingCommissionOrderAmount > 0 || sharingCommissionChannelOrderAmount > 0) {
                    orderAmountAfter = order.getPrice() - Math.addExact(sharingCommissionOrderAmount, sharingCommissionChannelOrderAmount);
                } else {
                    orderAmountAfter = order.getPrice();
                }
                //分账
                OrderInfo sharingProfitOrder = new OrderInfo();
                sharingProfitOrder.setOrderNo(orderNo);
                sharingProfitOrder.setActivityId(order.getActivityId());
                sharingProfitOrder.setCategory(SharingProfitOrderTypeEnum.VIDEO_ORDER.name());
                sharingProfitOrder.setTotalFee(orderAmountAfter);
                sharingProfitOrder.setPayTime(Date.from(order.getPayTime().atZone(ZoneId.systemDefault()).toInstant()));
                sharingProfitOrder.setTransactionId(transactionId);
                sharingProfitOrder.setAppId(order.getAppId());
                sharingProfitOrder.setMechantId(order.getMerchantId());
                sharingProfitOrder.setMechantName(order.getMerchantName());
                merchantSharingProfitService.doSharingProfit(sharingProfitOrder);
                log.warn("UserCourseOrderService,dealOrderPaySuccess,orderNo:{} pay success", orderNo);
                return;
            default:
                break;
        }
    }

    public UserCourseOrder findOrderByOrderId(String orderId) {
        return mongoTemplate.findOne(Query.query(Criteria.where("id").is(orderId)), UserCourseOrder.class);
    }

    public void rollbackRufundOp(String applyId) {
        Query query = Query.query(Criteria.where("id").is(applyId));
        Update update = Update.update("status", 0);
        mongoTemplate.updateFirst(query, update, CourseOrderRefundApply.class);
    }

    public GoodsOrderDTO buildRefundOrderParam(UserCourseOrder order) {
        GoodsOrderDTO dto = new GoodsOrderDTO();
        dto.setRefundNo(order.getRefundNo());
        dto.setOrderNo(order.getOrderNo());
        dto.setOpenId(order.getOpenId());
        dto.setPrice(order.getPrice());
        dto.setRefundPrice(order.getPrice());
        dto.setUserId(order.getUserId());
        dto.setAppId(order.getAppId());
        return dto;
    }

    public void passRefundApply(UserCourseOrder order, String applyId) {
        String refundOrderNo = IdGeneratorUtils.generateRCourseNo();
        // 获取商户信息
        WechatMerchantConfig merchantInfo = wechatPayService.getWechatMerchantConfigById(order.getMerchantId());
        // 退款
        order.setRefundNo(refundOrderNo);
        Triple<Boolean, Map, String> re = wechatPayService.refund(buildRefundOrderParam(order), merchantInfo);
        log.info("CourseOrderService,refundOrder,orderNo:{} refund result:{}", order.getOrderNo(), re);
        if (!re.getLeft()) {
            rollbackRufundOp(applyId);
            throw new BusinessException(re.getRight());
        }
        Update orderUpdate = Update.update("status", CourseOrderStatusEnum.REFUND_COMPLETE.getValue());
        orderUpdate.set("refundNo", refundOrderNo);
        orderUpdate.set("refundTime", LocalDateTime.now());
        // 通过更新订单状态
        Query orderQuery =
                Query.query(Criteria.where("id").is(order.getId()).and("status").is(CourseOrderStatusEnum.REFUND_APPLY.getValue()));
        UpdateResult result = mongoTemplate.updateFirst(orderQuery, orderUpdate, UserCourseOrder.class);
        log.info("CourseOrderService,refundOp,orderNo:{} pass update result:{}", order.getOrderNo(), result);
        // 订单更新成功，操作退款
        if (result.getModifiedCount() > 0) {
            // 重置课程活动状态信息
            userVideoService.dealRefundUserActivity(order.getUserId(), order.getAppId(), order.getActivityId(),
                    order.getCourseId());
            //移除用户答题记录
            userQaInfoService.removePassedRefundQa(order.getUserId(), order.getActivityId());
            //移除用户证书信息
            userCaService.removeUserCaByUserIdAndActivityId(order.getUserId(), order.getActivityId());
            //移除报名信息
            userParticipateActivityInfoService.removeSignUpByUserIdAndActivityId(order.getUserId(),
                    order.getActivityId());
            merchantSharingProfitService.doRefund(order.getOrderNo());
        }
    }

    public void rejectedRefundApply(String orderNo) {
        // 驳回更新订单状态
        Query orderQuery =
                Query.query(Criteria.where("orderNo").is(orderNo).and("status").is(CourseOrderStatusEnum.REFUND_APPLY.getValue()));
        UpdateResult result = mongoTemplate.updateFirst(orderQuery, Update.update("status",
                CourseOrderStatusEnum.PAY_SUCCESS.getValue()), UserCourseOrder.class);
        log.info("CourseOrderService,refundOp,orderNo:{} not pass update result:{}", orderNo, result);
    }

    public boolean updateOrderExpire(UserCourseOrder courseOrder) {
        // 失效更新订单状态
        List<Integer> statusList = Lists.newArrayList(CourseOrderStatusEnum.NOT_PAY.getValue());
        Query orderQuery = Query.query(Criteria.where("id").is(courseOrder.getId()).and("status").in(statusList));
        UpdateResult result = mongoTemplate.updateFirst(orderQuery, Update.update("status",
                CourseOrderStatusEnum.EXPIRED.getValue()), UserCourseOrder.class);
        log.info("CourseOrderService,updateOrderExpire,orderNo:{} expire order update result:{}",
                courseOrder.getOrderNo(), result);
        return result.getModifiedCount() > 0;
    }

    /**
     * 课程订单退款申请
     *
     * @param apply
     * @return
     */
    public boolean refundApply(CourseOrderRefundApplyReq apply) {
        log.info(":>>> 开始处理退款申请:{}", JSON.toJSON(apply));
        //校验订单
        Query orderQuery = Query.query(Criteria.where("id").is(apply.getOrderId()));
        UserCourseOrder order = mongoTemplate.findOne(orderQuery, UserCourseOrder.class);
        if (order == null) {
            throw new BusinessException("订单信息不存在");
        }
        if (order.getStatus().equals(CourseOrderStatusEnum.REFUND_COMPLETE.getValue())) {
            throw new BusinessException("订单已经退款");
        }
        if (order.getStatus().equals(CourseOrderStatusEnum.REFUND_APPLY.getValue())) {
            throw new BusinessException("订单退款申请中");
        }
        if (!order.getStatus().equals(CourseOrderStatusEnum.PAY_SUCCESS.getValue())) {
            throw new BusinessException("订单不是支付状态不能申请退款");
        }
        CourseOrderRefundApply refundApply = mongoTemplate.findOne(Query.query(Criteria.where("orderId").is(apply.getOrderId())
                .and("status").is(0)), CourseOrderRefundApply.class);
        if (refundApply != null) {
            throw new BusinessException("已经存在申请中的退款");
        }
        // 处理退款操作
        orderQuery.addCriteria(Criteria.where("status").is(CourseOrderStatusEnum.PAY_SUCCESS.getValue()));
        Update update = Update.update("status", CourseOrderStatusEnum.REFUND_APPLY.getValue());
        UpdateResult result = mongoTemplate.updateFirst(orderQuery, update, UserCourseOrder.class);
        log.info("CourseOrderService,refundApply,orderId:{} update order result:{}", apply.getOrderId(), JSONObject.toJSONString(result));
        if (result.getModifiedCount() <= 0) {
            throw new BusinessException("退款申请失败");
        }
        // 申请成功
        refundApply = new CourseOrderRefundApply();
        refundApply.setApplyReason(apply.getReason());
        refundApply.setOrderId(order.getId());
        refundApply.setOrderNo(order.getOrderNo());
        refundApply.setApplyTime(LocalDateTime.now());
        refundApply.setStatus(0);
        mongoTemplate.insert(refundApply);
        return true;
    }
}
